package com.sakila.action;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.ServletContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.servlet.ModelAndView;

import com.sakila.pojo.Staff;
import com.sakila.pojo.Store;
import com.sakila.pojo.other.Page;
import com.sakila.service.StaffService;
import com.sakila.service.StoreService;

//@Controller
public class ViewListMVC implements ServletContextAware{

	private StaffService staffService;
	private StoreService storeService;
	private String contextPath;

	public StaffService getStaffService() {
		return staffService;
	}
	@Autowired
	public void setStaffService(StaffService staffService) {
		this.staffService = staffService;
	}

	public StoreService getStoreService() {
		return storeService;
	}
	@Autowired
	public void setStoreService(StoreService storeService) {
		this.storeService = storeService;
	}

	@RequestMapping(value="/viewList", method=RequestMethod.GET)
	public ModelAndView execute(@RequestParam("to") String to){		
		ModelAndView mv = createModelView(to);
		return mv;
	}

	private ModelAndView createModelView(String to) {
		ModelAndView mv = new ModelAndView();
		mv.setViewName(to);
		switch (to) {
		case "staff":
			staffService(mv);
			break;
		case "store":
			storeService(mv);
			break;
		default:
			mv.setViewName("index");
			//log exception
			break;
		}
		return mv;
	}
	
	private void staffService(ModelAndView mv){
		List<Staff> list = staffService.findAll(new Page());
		for (Staff staff : list) {
			byte[] picture = staff.getPicture();
			String fileName = "staff_" + staff.getId() + ".jpg";
			File file = new File(contextPath + "images/" + fileName);
			System.out.println(file.getPath());
			if(!file.exists() && picture != null){
				try(OutputStream os = new FileOutputStream(file)){
					os.write(picture);
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		mv.addObject("list", list);
	}
	
	private void storeService(ModelAndView mv){
		List<Store> list = storeService.findAll(new Page());
		mv.addObject("list", list);
	}
	
	@Override
	public void setServletContext(ServletContext servletContext) {
		this.contextPath = servletContext.getRealPath("/");
	}
}
